package com.hotchpotch.base;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.List;

public abstract class BaseRecyclerAdapter<T> extends RecyclerView.Adapter<BaseViewHolder> {
    private Context context;
    private List<T> list;
    private int layoutId;
    private LayoutInflater inflater;
    private OnItemClick onItemClick;

    public BaseRecyclerAdapter(Context context, int layoutId) {
        this.context = context;
        this.layoutId = layoutId;
        this.inflater = LayoutInflater.from(context);
    }

    /**
     * 设置数据
     *
     * @param list
     */
    public void setData(List<T> list) {
        this.list = list;
        notifyDataSetChanged();
    }

    /**
     * 设置点击事件监听
     * @param onItemClick
     */
    public void setOnItemClick(OnItemClick onItemClick) {
        this.onItemClick = onItemClick;
    }

    @Override
    public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(layoutId, parent, false);
        BaseViewHolder viewHolder = new BaseViewHolder(view);
        return viewHolder;
    }

    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }

    @Override
    public void onBindViewHolder(BaseViewHolder holder, final int position) {
        onBind(holder, list.get(position), position);
        holder.getItemView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onItemClick != null) {
                    onItemClick.onClick(v, position);
                }
            }
        });
        holder.getItemView().setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (onItemClick != null) {
                    onItemClick.onLongClick(v, position);
                }
                return false;
            }
        });
    }

    //抽象方法，让子类继承实现
    public abstract void onBind(BaseViewHolder holder, T t, int position);

    /**
     * 点击事件的监听接口
     */
    public interface OnItemClick {
        void onClick(View v, int position);

        void onLongClick(View v, int position);
    }
}
